package com.eddie.cglib;

import com.eddie.context.TenantContext;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Eddie
 */
public class TenantSelectorMethodInterceptor implements MethodInterceptor {
    private final Map<String, Object> beanMap;

    public TenantSelectorMethodInterceptor() {
        beanMap = new ConcurrentHashMap<>();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        String mart = TenantContext.get();
        Object object = beanMap.getOrDefault(mart, beanMap.get("all"));
        return method.invoke(object, args);
    }

    public void addBean(String[] marts, Object bean) {
        for (String mart : marts) {
            beanMap.put(mart, bean);
        }
    }
}
